package org.viettan.android.main.activities;

import java.util.Date;

import org.viettan.android.main.R;
import org.viettan.android.main.activities.common.VietTanBaseActivity;
import org.viettan.android.main.io.cache.CacheUtility;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;

import com.google.inject.Inject;

/**
 * The splash screen that is displayed during the application load. This activity also goes through
 * the database and cleans up old files.
 */
public class SplashActivity extends VietTanBaseActivity {

    @Inject
    CacheUtility cacheUtility;

    private final int SPLASH_DISPLAY_TIME = 5 * 1000;
    private boolean active = true;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.splash);

	// determine when to stop the splash screen
	final long splashEndTime = new Date().getTime() + SPLASH_DISPLAY_TIME;

	// pre-cache content on a different background thread
	new PreCacheContentTask().execute();

	// thread for displaying the SplashScreen
	Thread splashTread = new Thread() {
	    @Override
	    public void run() {
		try {
		    // wait until we have displayed the splash screen long enough
		    while (active && (new Date().getTime() < splashEndTime)) {
			sleep(100);
		    }
		} catch (InterruptedException e) {
		    // do nothing
		} finally {
		    finish();
		    startActivity(new Intent(SplashActivity.this, RootActivity.class));
		}
	    }
	};
	splashTread.start();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
	if (event.getAction() == MotionEvent.ACTION_DOWN) {
	    active = false;
	}
	return true;
    }

    /**
     * Pre-caches content on a background thread.
     */
    private class PreCacheContentTask extends AsyncTask<Void, Void, Void> {
	@Override
	protected Void doInBackground(Void... ignored) {
	    cacheUtility.preCacheContent();
	    return null;
	}
    }
}
